package com.sdx.console.orgmain.web;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.file.FileService;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.orgmain.entity.*;
import com.sdx.console.orgmain.service.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;

import java.util.Date;
import java.util.List;


/**
 * orgmain 接口
 */
@RequestMapping("/orgmain/orgmain")
@Controller
public class OrgMainController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(OrgMainController.class);
    private static final String MODEL = "/orgmain/orgmain";


    @Resource
	private OrgMainService orgmainService;

    @Resource
    private FileService fileService;

    @Resource
    private ResCloudFileService resCloudFileService;

	@Resource
	private BaseDataService baseDataService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		OrgMain orgMain = new OrgMain();
		orgMain.setOrgPid(1);
		//省份列表
		view.addObject("provinceList",baseDataService.getAllProvince());
		// 上级组织列表
		view.addObject("orgMainList",orgmainService.template(orgMain," org_pid desc"));
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("orgmain.orgmain.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("orgmain.orgmain.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Long orgId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        OrgMain orgmain = orgmainService.queryById(orgId);
        view.addObject("orgmain", orgmain);
		setPageParam(view,request);
		try {
			view.addObject("orgmainJson", JacksonUtils.toJsonString(orgmain,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("orgmain.orgmain.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("orgmain.orgmain.query")
    @ResponseBody
    public JsonResult<PageQuery> list(OrgMain condtion)
    {
        PageQuery page = condtion.getPageQuery();
        orgmainService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,OrgMain orgmain,HttpServletRequest request
							,MultipartFile mainImgFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/orgmain/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(mainImgFile)) {
			try
			{
		        String mainImgFileNamePair = FileUtils.upload(subPath,mainImgFile);
		        String mainImgStoreFile = mainImgFileNamePair.split("::")[0];
		        mainImgStoreFile = subPath+mainImgStoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+mainImgStoreFile,bucketName,mainImgStoreFile.substring(1));
				String mainImgUrl = "https://sdxcomm."+ConfigService.ossDomain+mainImgStoreFile;
				orgmain.setMainImg(mainImgUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,mainImgStoreFile,mainImgUrl,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			orgmain.setCreatedTime(new Date());
			orgmain.setUpdatedTime(new Date());
			orgmain.setUpdatedBy(String.valueOf(user.getId().intValue()));
			orgmain.setUpdatedName(user.getName());
			orgmainService.save(orgmain);
		} else {
			orgmain.setUpdatedTime(new Date());
			orgmain.setUpdatedBy(String.valueOf(user.getId().intValue()));
			orgmain.setUpdatedName(user.getName());
			orgmainService.updateTemplate(orgmain);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("orgmain.orgmain.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)OrgMain orgmain,HttpServletRequest request
							,@RequestParam("mainImgFile") MultipartFile mainImgFile
		)
    {

        return save(true,orgmain,request
					,mainImgFile
		);
    }

    @PostMapping("/update.json")
    @Function("orgmain.orgmain.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  OrgMain orgmain,HttpServletRequest request
							,@RequestParam("mainImgFile") MultipartFile mainImgFile) {
		return save(false,orgmain,request,mainImgFile);
    }

    @GetMapping("/view.json")
    @Function("orgmain.orgmain.query")
    @ResponseBody
    public JsonResult<OrgMain>queryInfo(Long orgId) {
        OrgMain orgmain = orgmainService.queryById( orgId);
        return  JsonResult.success(orgmain);
    }

    @PostMapping("/delete.json")
    @Function("orgmain.orgmain.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        orgmainService.batchDelOrgMain(idList);
        return JsonResult.success();
    }

	/**
	 *  图片上传
	 * @param file
	 * @return
	 */
	@RequestMapping("/upload.json")
	@ResponseBody
	public JSONObject uploadImg(MultipartFile file) {
		JSONObject jsobject = new JSONObject();
		String dir = DateUtil.now("yyyyMMdd");
		String subPath = "/images/orgmain/"+dir+"/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(file)) {
			try
			{
				String fileNamePair = FileUtils.upload(subPath,file);
				String storeFile = fileNamePair.split("::")[0];
				storeFile = subPath+storeFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
				String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
				jsobject.put("url",url);
				jsobject.put("state", "SUCCESS");
				jsobject.put("title", "");
				jsobject.put("original", "");
				resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","学校logo");
			}catch(Exception e) {
				e.printStackTrace();
				jsobject.put("state", "FAIL");
				jsobject.put("title", "");
				jsobject.put("original", "");
				jsobject.put("url","");
			}
		}
		return jsobject;
	}
    

}
